package com.goparry.taskman.browse;

import java.util.Collections;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.goparry.taskman.GLOBAL;
import com.goparry.taskman.R;
import com.goparry.taskman.repository.RObject;
import com.goparry.taskman.repository.RObject.SortBy;
import com.goparry.taskman.restclient.AsyncRestClientRObjects;
import com.goparry.taskman.restclient.RESTUtilities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

/**
 * @author davidp
 * ListFragment to manage the browse and search results tab
 * To reduce the number of network calls this class implements a stack
 * to store the hierarchy contents above the current level. This means that when
 * the user navigates back up the hierarchy we can pop data off the stack,
 * but when the user navigates down the hierarchy we make server calls and pop the
 * data onto the stack.
 */

public class BrowseFragment extends ListFragment implements OnClickListener {
	List<RObject> mRObjects;				// Stores the current list of objects
	Stack<List<RObject>> browseStack;	// This stack is used to cache folders so we don't
										// have to re-fetch data as we navigate back up the tree
	//OnInitialSelectionListener mInitialSelectionListener;
	BrowseListeners mBrowseListeners;
	String mActivityName;

	
	// Interface that allows the parent BrowseActivity to handle list selections
	public interface BrowseListeners {
		public void onDocumentSelected(RObject rObject);
		public List<RObject> onFolderSelected(String folderID);
		public List<RObject> onInitialSelection();
		public String onGetExtraString();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mBrowseListeners = (BrowseListeners) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement BrowseListeners");
		}
	}

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
		// Inflate the layout for this fragment
        View thisView = inflater.inflate(R.layout.browsefragment, container, false);

		// Set up the Navigation buttons
		ImageButton btn = (ImageButton)thisView.findViewById(R.id.home);
		btn.setOnClickListener(this);
		btn = (ImageButton)thisView.findViewById(R.id.up);
		btn.setOnClickListener(this);

		// This fragment supprts two modes of operation
		// 1. Browse: classic folder browse navigation
		// 2. Search Results: displays the results of a search (text, barcode, geo-locations, nfc, etc.
		View view;
		if (mActivityName.equalsIgnoreCase(GLOBAL.BROWSE_ACTIVITY)) {
			view = thisView.findViewById(R.id.search_criteria);
			view.setVisibility(8); // VISIBLE	
			view = thisView.findViewById(R.id.navigation_group);
			view.setVisibility(0); // GONE			
		} else if (mActivityName.equalsIgnoreCase(GLOBAL.SEARCH_ACTIVITY)) {
    		TextView textView = (TextView)thisView.findViewById(R.id.search_criteria);
    		textView.setVisibility(0); // VISIBLE	
    		textView.setText("Results for: " + mBrowseListeners.onGetExtraString());
			view = thisView.findViewById(R.id.navigation_group);
			view.setVisibility(8); // GONE			
		} else if (mActivityName.equalsIgnoreCase(GLOBAL.TASK_ACTIVITY)) {
    		TextView textView = (TextView)thisView.findViewById(R.id.search_criteria);
    		textView.setVisibility(0); // VISIBLE	
    		textView.setText("Supporting documents: ");
			view = thisView.findViewById(R.id.navigation_group);
			view.setVisibility(8); // GONE			
			
		}
        return thisView;
    }

    @Override
	public void onCreate(Bundle icicle){ 
		super.onCreate(icicle); 
		// Get the parent activity that instantiated this fragment.
        mActivityName = getActivity().getTitle().toString();
        
        // Get the initial data to display in the ListView.
        // Browse: this is the list of Vaults
        // Search: this is the search results
        mRObjects = mBrowseListeners.onInitialSelection();
        //mRObjects = mActivity.onInitialSelection();
        Collections.sort(mRObjects);
        refreshAdapter();

		// Push the Home list on to the stack
        browseStack = new Stack<List<RObject>>();
	}
    
 	@Override
	public void onListItemClick(ListView parent, View v, int position, long id) {
		// This handles the selection of an item in the Browse ListView
		RObject rObject = mRObjects.get(position);

        if (rObject.getIsContainer()) {
        	// The user has selected a folder so we need to get its contents
    		// Push the current list on to the stack before getting the new list
            browseStack.push(mRObjects);
	        mRObjects = mBrowseListeners.onFolderSelected(rObject.getID());
	        refreshAdapter();
         } else {
			// This is a document so we need to update the DocumentFragment
        	// DocumentActivity
        	 mBrowseListeners.onDocumentSelected(rObject);
		}

	}
 	// Service the Home and Up navigation buttons on the browse tab.
	@Override
	public void onClick(View view) {
		int viewID = view.getId();
		if (viewID==R.id.home) {
			if (!browseStack.empty()) {
				mRObjects = browseStack.get(0);
				browseStack.clear();
				refreshAdapter();				
			}
			
		} else if (viewID==R.id.up) {
			if (!browseStack.empty()) {
				mRObjects = browseStack.pop();
				refreshAdapter();				
			}
		}
		
	}
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		// Handle this activities menu items
//		switch (item.getItemId()) {
//		case R.id.sort:
//			// Change the sort order
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);
//			int currentSortOrder = -1;
//			switch (RObject.sortBy) {
//			case NAME:
//				currentSortOrder = 0;
//				break;
//			case STATUS:
//				currentSortOrder = 1;
//				break;
//			}
//			builder.setTitle("Sort");
//			builder.setSingleChoiceItems(R.array.docsSortOptions, currentSortOrder, new DialogInterface.OnClickListener() {
//			    public void onClick(DialogInterface dialog, int item) {
//			        Resources res = getResources();
//			    	TypedArray items = res.obtainTypedArray(R.array.docsSortOptions);
//			    	if (items.getString(item).equalsIgnoreCase("Name")) {
//			            RObject.sortBy = SortBy.NAME;
//			            refreshAdapter();
//			        } else if (items.getString(item).equalsIgnoreCase("Status")) {
//				        RObject.sortBy = SortBy.STATUS;
//				        refreshAdapter();
//			        }
//			        dialog.dismiss();
//			    }
//			});
//			AlertDialog alert = builder.create();
//			alert.show();
//			return true;
//		default:
//			return super.onOptionsItemSelected(item);
//		}
//	}
//	@Override
//	public boolean onPrepareOptionsMenu(Menu menu) {
//		// Enable the sort menu for this activity
//		MenuItem item = menu.findItem(R.id.sort);
//		item.setEnabled(true);
//		item.setVisible(true);
//		return true;
//	}
	public void refreshAdapter() {
		// Refresh the ListView after a Sort request or change in data
        Collections.sort(mRObjects);
		setListAdapter(new DocumentAdapter(getActivity(), R.layout.document_row,R.id.name,mRObjects));
	}
}
